﻿using System;
using System.Collections.Generic;

namespace SAFPodcast.WP8.Fwk.Cache
{
    public class SimpleCache
    {
        private IDictionary<String, object> items;

        public SimpleCache()
            : base()
        {
            items = new Dictionary<string, object>();
        }

        public void Put<T>(String key, T item)
        {
            items[key] = item;
        }

        public T Get<T>(String key)
        {
            T result = default(T);
            if (items.ContainsKey(key))
            {
                result = (T)items[key];
            }

            return result;
        }

        public bool TryGet<T>(String key, ref T item)
        {
            if (!items.ContainsKey(key))
            {
                item = default(T);
                return false;
            }
            else
            {
                var itemAsObject = items[key];
                if (itemAsObject == null)
                {
                    item = default(T);
                    return false;
                }
                else if (itemAsObject is T)
                {
                    item = (T)itemAsObject;
                    return true;
                }
                else
                {
                    item = default(T);
                    return false;
                }
            }
        }

        public bool Exist(string key)
        {
            return items.ContainsKey(key);
        }
    }
}
